package com.wjk.kylin.mall.gateway.exception;

import com.alibaba.fastjson.JSON;
import com.wjk.kylin.mall.common.core.dto.base.BaseOutDTO;
import com.wjk.kylin.mall.common.core.exception.BaseException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author wangjkui
 * @description 全局的的异常拦截器（拦截所有的控制器）（带有@RequestMapping注解的方法上都会拦截）
 * @date 2020/5/22
 */
@Slf4j
@Order(-1)
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 拦截未知的异常
     */
    @ExceptionHandler(Exception.class)
    public BaseOutDTO handleException(Exception e) {
        log.error("服务器未知异常:{}", e.getMessage(), e);
        return BaseOutDTO.error(e.getMessage());
    }

    /**
     * 拦截未知的运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    public BaseOutDTO handleRuntimeException(RuntimeException e) {
        log.error("服务器未知运行时异常:{}", e.getMessage(), e);
        return BaseOutDTO.error(e.getMessage());
    }

    /**
     * 拦截业务异常
     */
    @ExceptionHandler(BaseException.class)
    public BaseOutDTO handleBusinessException(BaseException e) {
        log.error("基础业务异常 e:{}", JSON.toJSONString(e.getError()));
        return BaseOutDTO.error(e.getError());
    }

}
